import sys
import os
import datetime

from http import HTTPStatus

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, "..", "common"))
sys.path.append(os.path.join(thisDir, "..", "..", "ui", "pu"))

import EJOConst
import EJOConfig
from SessionManager import SessionManager

import logging
logger = logging.getLogger(__name__)

class EJOHandlerBase():
    def __init__(self):
        self.__cmd = None
        self.__params = None

    #
    # Handler Helpers
    #

    def Handle(self, cmd, params):
        self.__cmd = cmd
        self.__params = params
        if self._doValidate() or EJOConfig.IGNORE_SESSION_VALIDATE:
            return self._doHandle()
        return False, HTTPStatus.UNAUTHORIZED, "Invalid session"

    def _doHandle(self):
        return False, HTTPStatus.NOT_IMPLEMENTED, "Not implemented"

    # It supports there must be "session" parameter defined
    # Handler should override this function if there is different situation
    def _doValidate(self):
        session = self._getParamValue(EJOConst.Session)
        return False if session is None else SessionManager().IsValidSession(session)

    #
    # Utilities
    #

    def _getParamValue(self, paramName):
        for param in self.__params:
            if param[0] == paramName:
                return param[1]
        return None

    def _convertToDateObj(self, dateString):
        try:
            return datetime.datetime.strptime(dateString, EJOConfig.DATE_FORMAT)
        except Exception as e:
            logger.error(f"Exception on parse date parameter: {dateString}")
            logger.error(e)
        return None
